package org.fatmansoft.teach.service;


import org.fatmansoft.teach.models.*;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.repository.PersonRepository;
import org.fatmansoft.teach.repository.StudentLogRepository;
import org.fatmansoft.teach.repository.StudentRepository;
import org.fatmansoft.teach.repository.UserRepository;
import org.fatmansoft.teach.util.CommonMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class StudentLogService {
    @Autowired
    StudentLogRepository studentLogRepository;
    @Autowired
    StudentRepository studentRepository;
    @Autowired
    PersonRepository personRepository;
    /*********************************************辅助方法***********************************************/

    //主键自增
    public synchronized Integer getNewStudentLogId(){
        Integer  id = studentLogRepository.getMaxId();  // 查询最大的id
        if(id == null){
            id = 1;
        } else{
            id = id+1;
        }
        return id;
    }

    //根据studentId获取Student实体
    public Student getStudent(Integer studentId) {
        Student student = null;
        if(studentId != null) {
            Optional<Student> x1 = studentRepository.findById(studentId);
            if(x1.isPresent()) {
                student = x1.get();
            }
        }
        return student;
    }
    //根据studentLogId获取某个特定日志
    public StudentLog getStudentLog(Integer studentLogId) {
        StudentLog studentLog = null;
        if(studentLogId != null) {
            Optional<StudentLog> x1 = studentLogRepository.findById(studentLogId);
            if(x1.isPresent()) {
                studentLog = x1.get();
            }
        }
        return studentLog;
    }
    //根据账号（学号）查找特定学生，用于搜索框查询。
    //如果只是点击编辑按钮的话，就不需要这个方法。因为此时可以直接用日志map里的id来找学生，没必要通过账号在后端再查一次
    public Student getStudentByPersonName(String personName){
        Optional<Person> person = personRepository.findByNum(personName);
        if(person.isPresent()){ //如果存在这个person
            Person p =person.get();
            Optional<Student> student = studentRepository.findByPersonPersonId(p.getPersonId());
            if(student.isPresent()){    //如果这个person是学生，返回学生
                return student.get();
            }
        }
        return null;
    }
/**********************************************接口业务代码**************************************************/
    //【查】根据学号、日志品种和日期范围查找符合要求的日志
    public DataResponse findAllLogByPersonNameAndDate(DataRequest dataRequest) {
        String num = dataRequest.getString("username");
        String sd = dataRequest.getString("startDate");
        String ed = dataRequest.getString("endDate");
        Integer type = dataRequest.getInteger("logType");
        Integer code = dataRequest.getInteger("code");  //审核码
        Student student = getStudentByPersonName(num);
        if (student == null && num!=null) {    //查无此人
            return CommonMethod.getReturnMessageError("未能找到该学号对应的学生");
        }
        List datalist = getLogMapList(student,num,sd,ed,type,code);
        return CommonMethod.getReturnData(datalist);
    }
    private List getLogMapList(Student student,String num,String startDate,String endDate,Integer type,Integer code) {
        List dataList = new ArrayList();
        List<StudentLog> LogList = new ArrayList<>();
        if(student==null){
            LogList = studentLogRepository.findByStudentIdAndDateStringBetweenAndLogTypeAndCode(null, startDate, endDate, type, code);
        }else {
            LogList = studentLogRepository.findByStudentIdAndDateStringBetweenAndLogTypeAndCode(student.getStudentId(), startDate, endDate, type, code);
        }
        if(LogList == null || LogList.isEmpty()) {
            //List最后一个项是学生姓名name
            Map name =new HashMap();
            Optional<Person> person = personRepository.findByNum(num);
            if(person.isPresent()) {
                Person p = person.get();
                name.put("name", p.getName());
                dataList.add(name);
            }
            return dataList;
        }
        for (StudentLog studentLog : LogList) {
            dataList.add(getMapFromLogList(studentLog));
        }
        //List最后一个项是学生姓名name
        Map name =new HashMap();
        Optional<Person> person = personRepository.findByNum(num);
        if(person.isPresent()) {
            Person p = person.get();
            name.put("name", p.getName());
            dataList.add(name);
        }
        return dataList;
    }
    public Map getMapFromLogList(StudentLog log) {
        Map m = new HashMap();
        if(log == null) {
            return m;
        }
        m.put("logType",log.getLog_type());
        m.put("date",log.getDate());
        m.put("reason",log.getReason());
        m.put("cost",log.getCost());
        m.put("studentNum",log.getStudent().getPerson().getNum());
        //m.put("code",log.getCode());    //返回状态码码？诶突然感觉好像也不用。只要前端发请求的时候规定好code。。。发过去的code就一定是收到的code
        m.put("studentLogId",log.getStudentLogId());    //重要！应当返回日志的Id
        return m;
    }


//********************************************************************************************************//
    //【删】根据StudentLogId删除日志内容
    @Transactional
    public DataResponse deleteLog(DataRequest dataRequest){
        Integer studentLogId = dataRequest.getInteger("studentLogId");
        studentLogRepository.deleteByStudentLogId(studentLogId);
        return CommonMethod.getReturnMessageOK();
    }
//********************************************************************************************************//
    //【改】根据StudentLogId修改日志内容
    public DataResponse logEditSave(DataRequest dataRequest) {
        //根据studentLogId编辑日志内容
        Integer studentLogId = dataRequest.getInteger("studentLogId");
        Map form = dataRequest.getMap("form"); //参数获取Map对象。内含log各个新信息

        //查找StudentLog实体类
        StudentLog log= getStudentLog(studentLogId);
        //log必然存在（通过点击编辑表格里的按钮才能触发此方法），我们直接进入填充log环节
        log.setLog_type(CommonMethod.getInteger(form,"logType"));
        log.setDate(CommonMethod.getString(form,"date"));
        log.setReason(CommonMethod.getString(form,"reason"));
        log.setCost(CommonMethod.getDouble(form,"cost"));
        //不要改审核码。这里都是审核通过的日志

        studentLogRepository.save(log);  // 修改保存
        return CommonMethod.getReturnData(log.getStudentLogId());  // 将studentLogId返回前端
    }
//********************************************************************************************************//
    //【增】根据username创建日志内容
    public DataResponse createLog(DataRequest dataRequest) {
        Student s =getStudentByPersonName(dataRequest.getString("username"));
        Integer code = dataRequest.getInteger("code");
        Map form = dataRequest.getMap("form");
        if(s==null){    //查无此人
            return CommonMethod.getReturnMessageError("未能找到该学号对应的学生");
        }
        StudentLog log = new StudentLog();
        log.setStudentLogId(getNewStudentLogId());
        log.setStudent(s);
        log.setLog_type(CommonMethod.getInteger(form,"logType"));
        log.setDate(CommonMethod.getString(form,"date"));
        log.setReason(CommonMethod.getString(form,"reason"));
        log.setCost(CommonMethod.getDouble(form,"cost"));
        log.setCode(code);
        studentLogRepository.saveAndFlush(log);
        return CommonMethod.getReturnData(log.getStudentLogId());  // 将studentLogId返回前端
    }
//********************************************************************************************************//
    //【审核】根据studentLogId更改日志审核码code
    public DataResponse examineLog(DataRequest dataRequest) {
        Integer code = dataRequest.getInteger("code");
        Integer studentLogId = dataRequest.getInteger("studentLogId");
        StudentLog log= getStudentLog(studentLogId);
        log.setCode(code);
        studentLogRepository.save(log);
        return CommonMethod.getReturnMessageOK();
    }
}
